package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.data.domain.DataUserRelation;
import com.ruoyi.data.service.IDataUserRelationService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * 代理信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDataUserRelationService userRelationService;

    /**
     * 获取代理列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/newList")
    public AjaxResult newList(SysDept dept) {
        LoginUser loginUser = getLoginUser();
        if (!loginUser.getUser().isAdmin()) {
            dept.setParentId(null);
        }
        List<SysDept> depts = deptService.selectLazyDeptList(dept);
        if (depts.size() > 0) {
            SysUser user;
            int userCount;
            List<DataUserRelation> userRelationList;
            DataUserRelation userRelation = new DataUserRelation();
            for (SysDept item : depts) {
                user = userService.selectUserByDeptIdForTeam(item.getDeptId());
                //求直属用户数量
                userRelation.setTopUserId(user.getUserId());
                userRelationList = userRelationService.selectDataUserRelationList(userRelation);
                item.setUserCount(userRelationList.size());
                //求团队用户数量
                userCount = userService.selectUserListCountByDeptId(user);
                if (item.getDeptId().longValue() == 100L) {
                    item.setTeamCount(userCount + 1);
                } else {
                    item.setTeamCount(userCount);
                }
                if (userCount == 0) {
                    item.setTeamCount(1);
                }
                if (item.getTeamCount() == 1) {
                    item.setHasChildren(false);
                }
                item.setTeamCount(item.getTeamCount() - 1);
                item.setDeptName(item.getDeptName() + "(" + user.getUserLevel() + ":" + item.getDeptCode() + ")");
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 获取代理列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询代理列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return AjaxResult.success(depts);
    }

    /**
     * 根据代理编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增代理
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "代理管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增代理'" + dept.getDeptName() + "'失败，代理名称已存在");
        }
        getDeptCode(dept);
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改代理
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "代理管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改代理'" + dept.getDeptName() + "'失败，代理名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return AjaxResult.error("修改代理'" + dept.getDeptName() + "'失败，上级代理不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.error("该代理包含未停用的子代理！");
        }
        if (StringUtils.isNullOrEmpty(dept.getDeptCode())) {
            getDeptCode(dept);
        }
        dept.setUpdateBy(getUsername());
        SysDept old = deptService.selectDeptById(deptId);
        if (!old.getDeptName().equals(dept.getDeptName())) {
            //同步用户
            SysUser user = userService.selectUserByDeptId(deptId);
            user.setNickName(dept.getDeptName());
            userService.updateUserProfile(user);
            //同步关系表 同步积分、订单、消费、库存
            userRelationService.updateDataUserRelationSync(user);
        }
        return toAjax(deptService.updateDept(dept));
    }

    private void getDeptCode(@RequestBody @Validated SysDept dept) {
        Random random = new Random();
        for (; ; ) {
            dept.setDeptCode(String.format("%05d", random.nextInt(99999)));
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptCodeUnique(dept))) {
                dept.setDeptCode(String.format("%05d", random.nextInt(99999)));
            } else {
                break;
            }
        }
    }

    /**
     * 删除代理
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "代理管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级代理,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("代理存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
